package com.yonyou.ucf.mdf.app.isvdxq.utils;

import com.yonyou.iuap.yms.param.SQLParameter;
import com.yonyou.iuap.yms.replace.CollectionUtil;
import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
//import com.yonyoucloud.wms01.common.HideField;
//import com.yonyoucloud.wms01.common.ShowField;
import lombok.SneakyThrows;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import javax.persistence.Column;
import javax.persistence.Table;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MyExtend {
    /**
     * 获取表名
     * @param entityClass
     * @return
     */
    public static String getTableName(Class<?> entityClass) {
        Annotation annotation = entityClass.getAnnotation(Table.class);
        if (annotation instanceof Table) {
            Table tableAnnotation = (Table) annotation;
            return tableAnnotation.name();
        }
        return null;
    }

    /**
     * 获取对象字段Name
     * @param entity
     * @return
     */
    public static String getFields(Object entity) {
        Class<?> clazz = entity.getClass();
        StringBuilder sb = new StringBuilder();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            sb.append(',' + field.getName());
        }

        return sb.toString().length() > 0 ? sb.toString().substring(1) : sb.toString();
    }
    public static String[] getFieldsToArray(Object entity){
        return getFields(entity).split(",");
    }

    public static List<Field> getAllFields(Class<?> type) {
        List<Field> fields = new ArrayList<>();
        for (Class<?> c = type; c != null; c = c.getSuperclass()) {
            for (Field field : c.getDeclaredFields()) {
                fields.add(field);
            }
        }
        return fields;
    }
    /**
     * 获取实体字段Name
     * @param clazz
     * @param type 0 默认展示 1 默认隐藏
     * @return
     * @param <T>
     */
//    public static <T> String getFields(Class<T> clazz, int type){
//        return getFields(clazz, type, false, null);
//    }
//    public static <T> String getFields(Class<T> clazz, Map<String, String> dict){
//        return getFields(clazz, 0, true, dict);
//    }
//    public static <T> String getFields(Class<T> clazz, int type, boolean camel, Map<String, String> dict) {
//        StringBuilder sb = new StringBuilder();
//        List<Field> fields = getAllFields(clazz);
//
//        for (Field field : fields) {
//            //Annotation[] annotations = field.getAnnotations();
//            String name = field.getName();
//            if (camel) {
//                String newname = toCamelCaseSource(name);
//                if (dict != null) dict.put(name, newname);
//                name = newname;
//            }
//            if (field.isAnnotationPresent(Column.class)) {
//                name = field.getAnnotation(Column.class).name();
//            }
//            if (type == 1 && field.isAnnotationPresent(ShowField.class)) {
//                sb.append(',' + name);
//            }
//            // 默认全部展示
//            else {
//                if (field.isAnnotationPresent(HideField.class)) continue;
//                sb.append(',' + name);
//            }
//        }
//
//        return sb.toString().length() > 0 ? sb.toString().substring(1) : sb.toString();
//    }
//    public static <T> String[] getFieldsToArray(Class<T> clazz){
//        return getFields(clazz, 0).split(",");
//    }

    /**
     * 驼峰转换
     * @param s
     * @return
     */
    public static String toCamelCase(String s) {
        if (s == null || s.isEmpty()) {
            return s;
        }
        if (!s.contains("_")) {
            // 如果不含下划线，则直接返回
            return s;
        }
        StringBuilder camelCaseStr = new StringBuilder();
        String[] parts = s.split("_");
        for (String part : parts) {
            camelCaseStr.append(part.substring(0, 1).toUpperCase());
            camelCaseStr.append(part.substring(1).toLowerCase());
        }
        return camelCaseStr.toString();
    }

    /**
     * 驼峰转下划线
     * Hutool
     * StrUtil.toUnderlineCase("helloWorld");
     * CaseFormat
     * CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "helloWorld");
     * @param s
     * @return
     */
    public static String toCamelCaseSource(String s) {
        if (s == null || s.isEmpty()) {
            return s;
        }
        if (!containsUpperCaseChar(s)) {
            // 如果不含大写，则直接返回
            return s;
        }
        char UNDER_LINE = '_';
        char pre = 0;
        StringBuilder camelCaseStr = new StringBuilder();
        for (int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if (Character.isUpperCase(ch)){
                if (pre != UNDER_LINE) {
                    camelCaseStr.append(UNDER_LINE);
                }
                camelCaseStr.append(Character.toLowerCase(ch));
            }
            else {
                camelCaseStr.append(ch);
            }
            pre = ch;
        }
        return camelCaseStr.toString();
    }
    public static boolean containsUpperCaseChar(String str) {
        return str.matches(".*[A-Z].*");
    }
    public static String getFieldValue(Object entity) throws IllegalAccessException{
        StringBuilder sb = new StringBuilder();
        Class<?> clazz = entity.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            Object value = field.get(entity);
            if (value != null) {
                sb.append(value.toString());
            }
        }

        return sb.toString();
    }

    /**
     * Mybatis SQL构造器创建
     * Mybatis-Plug 手动检测 SqlInjectionUtils.check()
     * @return
     */
    public static String buildSelectUsersSql(@Param("status") String status) {
        String sqlString = new SQL(){{
            SELECT("id, username, email");
            FROM("users");
            WHERE("status = #{status}");
        }}.toString();
        return sqlString;
    }

    /**
     * 获取分页数据
     * @param clazz
     * @param action
     * @param param
     * @return
     * @param <T>
     * @param <TS>
     * @param <TP>
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @SneakyThrows
    public static <T,TS,TP> DataResult<T> SelectPage2(Class<TS> clazz, String action, TP param) {
        DataResult<T> result = new DataResult<>(1,"查询成功");
        Method method = clazz.getMethod(action, param.getClass());
        List<T> dataList = (List<T>) method.invoke(clazz.newInstance(), param);
        Method method2 = clazz.getMethod("SelectListCount", String.class);
        int count = (int) method2.invoke(clazz.newInstance(), param);
        result.setDataList(dataList);
        result.setTotalSize(count);
        return result;
    }
    @SneakyThrows
    public static <T,TS,TP> DataResult<T> SelectPage(String className, String action, TP param) {
        DataResult<T> result = new DataResult<>(1,"查询成功");
        //获取当前上下文环境，spring容器
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        //获取类实例
        Class<?> clazz = wac.getBean(className).getClass();
        Method method = clazz.getMethod(action, param.getClass());
        List<T> dataList = (List<T>) method.invoke(clazz.newInstance(), param);
        Method method2 = clazz.getMethod("SelectListCount", String.class);
        int count = (int) method2.invoke(clazz.newInstance(), param);
        result.setDataList(dataList);
        result.setTotalSize(count);
        return result;
    }
    private static ApplicationContext applicationContext;

    /**
     * List参数 转sqlString
     * 建议尽可能 @Select foreach 注解
     * @param key
     * @param ids
     */
    public static String getList2SQL(String key, List<String> ids){
        String sbString = "";
        if (ids!=null && ids.size() > 0) {
            StringBuffer sb = new StringBuffer();
            sb.append(key + " in (");
            for (int i = 0; i < ids.size(); i++) {
                sb.append("#{strList[" + i + "]},");
            }
            sbString = sb.substring(0, sb.length() - 1)+")";
        }
        return sbString;
    }

    /**
     * 检测 List<String> sql参数
     * @param strList
     * @param sqlBuilder
     * @param parameter
     */
    public static void checkSQLParamsList(List<String> strList, StringBuffer sqlBuilder, SQLParameter parameter){
        if (CollectionUtil.isNotEmpty(strList)) {
            sqlBuilder.append(" ( ");
            String separator0 = " , ";
            for (int index = 0; index < strList.size(); index++) {
                String item = strList.get(index);
                sqlBuilder.append(" ? ");
                parameter.addParam(item);
                if (index < strList.size() - 1) {
                    sqlBuilder.append(separator0);
                }
            }
            sqlBuilder.append(" ) ");
        }
    }
}
